package stateManager;
import java.util.Map;
import java.util.HashMap;
import main.GameTree;


public class StateManager {
	
	private static StateManager stateManager = null;
	protected State currentState = null;
	protected State previousState = null;
	protected State upcomingState = null;
	protected Map<String, State> stateHashMap = new HashMap<String, State>();
	private boolean changedStates = false;
	private boolean needToChangeStates = false;
	private StateManager(){
		
	}
	public synchronized static StateManager getInstance() {
		   if(stateManager == null) {
			   stateManager = new StateManager();
		   }
		   return stateManager;
		}
	
	public void addStateToStateManager(String key, State value){
		this.stateHashMap.put(key, value);
	}
	
	public State getStateByKey(String key){
		return this.stateHashMap.get(key);
	}
	
	public State getCurrentState(){
		return this.currentState;
	}
	
	public void setCurrentStateByKey(String key){
		this.previousState = this.currentState;
		this.currentState = getStateByKey(key);
		
	}

	public void transitionStates(String key){
		this.currentState = this.currentState.getNextState(key);
		changedStates = true;
	}
	
	public void setStateTransitions(String stateAKey, String stateBKey, String transitionCode){
		State stateA = getStateByKey(stateAKey);
		State stateB = getStateByKey(stateBKey);
		stateA.setTransition(transitionCode, stateB);
	}
	
	public boolean didChangeStates(){
		if(changedStates == true){
			changedStates = false;
			return true;
		}
		return changedStates;
	}
	
	public GameTree initState(GameTree gameTree){
		return this.getCurrentState().init(gameTree);
	}
	public boolean isCurrentStateInitialized(){
		return this.getCurrentState().isInitialized();
	}
	public void setUpcomingState(String key){
		this.upcomingState = getStateByKey(key);
		this.needToChangeStates = true;
	}
	public void changeToUpcomingState(){
		if(this.needToChangeStates == false){
		}
		else{
			this.needToChangeStates = false;
			this.previousState = getCurrentState();
			this.currentState = upcomingState;
			this.upcomingState = null;
			this.changedStates = true;
		}
	}
	
	public void changeStatesOnNextLoop(State state, String transitionCode){
		if(state.getNextState(transitionCode)!= null){
			this.upcomingState = state.getNextState(transitionCode);
			this.upcomingState.setInitialized(false);
			this.needToChangeStates = true;
		}
	}
	
	
}
